//
//  HZCFloatView.swift
//  HZCFloatingView-Swift
//悬浮可拖动的view
//  Created by Apple on 2018/8/10.
//  Copyright © 2018年 AiChen smart Windows and doors technology co., LTD. All rights reserved.
//

import UIKit

class HZCFloatView: UIView {
    
    var clickAction:(()->())?
 
    private var lastPoint = CGPoint.zero
    
    private var pointInSelf = CGPoint.zero
    
    init(frame: CGRect,imgStr:String) {
        super.init(frame: frame)
        self.layer.contents = UIImage(named: imgStr)?.cgImage
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()! as! UITouch
        lastPoint = touch.location(in: self.superview)
        pointInSelf = touch.location(in: self)
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()! as! UITouch
        let currentPoint = touch.location(in: self.superview)
        
        //计算当前的中心点
        let centerX = currentPoint.x - (frame.width/2 - pointInSelf.x)
        let centerY = currentPoint.y - (frame.height/2 - pointInSelf.y)
        //修改中心点的坐标
        let x = max(30.0, min(UIScreen.main.bounds.width - 30.0, centerX))
        let y = max(30.0, min(UIScreen.main.bounds.height - 30.0, centerY))
        
        center = CGPoint(x: x, y: y)
        
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()! as! UITouch
        let currentPoint = touch.location(in: self.superview)
        
        if __CGPointEqualToPoint(lastPoint, currentPoint) {
            /// 点击操作
            if let clickAction = self.clickAction {
                clickAction()
            }
            return
        }

        
        
        distanceLeftOrRightMarginNeedAnimationMove(isAnimation: true)
        
        
    }
    
    ///计算左右的距离并且是否需要动画移动
    private func distanceLeftOrRightMarginNeedAnimationMove(isAnimation: Bool) {
        
        let duartion = isAnimation ? 0.25:0
        
        let leftMargin = center.x
        let rightMargin = UIScreen.main.bounds.width - leftMargin
        
        let centerX = leftMargin < rightMargin ? 40.0 : UIScreen.main.bounds.width - 40.0
        
        UIView.animate(withDuration: duartion) {
            self.center = CGPoint(x: centerX, y: self.center.y)
        }
    }
}


